package com.wen.utils;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author
 * @Create 2019-01-25 11:30
 * @Version 1.0
 * @Description 文件下载
 */
public class FileCopyUtils extends FileUtils {


    /**
     * 网络地址下载文件,针对org.apache.commons.io.FileUtils没有user-agent会出现403问题做优化
     * @param url
     * @param file
     */
    public static void copyURLToFile(URL url,File file){

        InputStream ism = null;
        try {
            HttpURLConnection conn=(HttpURLConnection)url.openConnection();
            conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36");
            ism = conn.getInputStream();
            if(ism!=null){
                OutputStream osm = new FileOutputStream(file);
                byte[] buff = new byte[1024];
                while (true) {
                    int readed = ism.read(buff);
                    if (readed == -1) {
                        break;
                    }
                    byte[] temp = new byte[readed];
                    System.arraycopy(buff, 0, temp, 0, readed);
                    osm.write(temp);
                }
                osm.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
